package ua.com.minus1.lookbattle;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import ua.com.minus1.lookbattle.models.CacheFolder;
import ua.com.minus1.lookbattle.models.CommonResult;
import ua.com.minus1.lookbattle.net.HttpFileCache;
import ua.com.minus1.lookbattle.net.HttpManager;
import ua.com.minus1.lookbattle.net.MultipartUploader;
import ua.com.minus1.lookbattle.utils.AppPreferences;
import ua.com.minus1.lookbattle.utils.BundleValues;

import java.io.File;
import java.io.IOException;
import java.util.zip.Inflater;

/**
 * Created with IntelliJ IDEA.
 * User: Igorek
 * Date: 11/3/12
 * Time: 10:15 PM
 * To change this template use File | Settings | File Templates.
 */
public class AddLookActivity extends SherlockFragmentActivity {

    private static final int TAKE_PICTURE = 0;
    private static final int SELECT_PICTURE = 1;

    private int mCatId;
    private AddLookConfirmFragment mConfirmFragment;
    private HttpFileCache mFileCache;
    private File mImageFile;
    private Bitmap mImageBitmap;
    private AppPreferences mAppPreferences;
    private boolean showConfirmFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_singlepane_empty);

        Bundle bundle = getIntent().getExtras();
        boolean useCamera = bundle.getBoolean(BundleValues.USE_CAMERA);
        mCatId = bundle.getInt(BundleValues.CAT_ID);

        mFileCache = new HttpFileCache(this, CacheFolder.HTTP_ADD_LOOK);
        mAppPreferences = new AppPreferences(this);

        /*LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View menuBtns = inflater.inflate(R.layout.action_bar_confirm, null);*/
        ActionBar actionBar = getSupportActionBar();
        //actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        actionBar.setDisplayShowTitleEnabled(false);
        actionBar.setDisplayShowHomeEnabled(false);
        //actionBar.setCustomView(menuBtns);

        showConfirmFragment = false;

        if(useCamera)
            takePicture();
        else
            pickPicture();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(showConfirmFragment)
            createFragment();
    }

    private void createFragment() {
        mConfirmFragment = AddLookConfirmFragment.newInstance(mImageFile.getPath());
        getSupportFragmentManager().beginTransaction()
                .add(R.id.root_container, mConfirmFragment, "confirm_fragment")
                .commit();
    }

    public void takePicture() {
        mImageFile = getEmptyFile("look.jpg");
        if(mImageFile != null){
            Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mImageFile));
            startActivityForResult(i, TAKE_PICTURE);
        }
    }

    public void pickPicture() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case TAKE_PICTURE:
                    BitmapFactory.Options opts = new BitmapFactory.Options();
                    opts.inJustDecodeBounds = true;
                    BitmapFactory.decodeFile(mImageFile.getPath(), opts);
                    //Log.i(AddLookActivity.class.getName(), opts.outWidth + "x" + opts.outHeight);


                    Toast.makeText(this, opts.outWidth + "x" + opts.outHeight, Toast.LENGTH_LONG)
                            .show();

//                    mImageBitmap = (Bitmap) data.getExtras().get("data");
//                    Toast.makeText(this, mImageBitmap != null? "captured bitmap height: "+ String.valueOf(mImageBitmap.getHeight()): "bitmap is null", Toast.LENGTH_SHORT)
//                            .show();
//                    Log.i(AddLookActivity.class.getName(), String.valueOf(mImageBitmap.getHeight()));
                    showConfirmFragment = true;
                    break;
                case SELECT_PICTURE:
                    Uri selectedImageUri = data.getData();

                    String fileManagerPath = selectedImageUri.getPath();
                    String galleryPath = getPath(selectedImageUri);

                    if(galleryPath != null)
                        mImageFile = new File(galleryPath);
                    else
                        mImageFile = new File(fileManagerPath);

                    showConfirmFragment = true;
                break;
            }
//            showConfirmFragment = true;

        } else {
            setResult(RESULT_CANCELED);
            finish();
        }

    }

    private String getPath(Uri uri) {
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery(uri, projection, null, null, null);

        if (cursor != null) {
            int columnIndex = cursor.getColumnIndex(projection[0]);
            if(columnIndex == -1)
                return null;
            cursor.moveToFirst();
            return cursor.getString(columnIndex);
        }
        return null;
    }

    private File getEmptyFile(String fileName) {
        File file = mFileCache.getFile(fileName);
        try {
            if (file.exists()) {
                file.delete();
                file.createNewFile();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        getSupportMenuInflater().inflate(R.menu.add_look, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.add_look_select:
                setResult(RESULT_OK);
                uploadLook();
                break;
            case R.id.add_look_cancel:
                setResult(RESULT_CANCELED);
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

   /* public void actionBarClick(View view)
    {
        switch (view.getId()) {
            case R.id.add_look_select_btn:
                *//* setResult(RESULT_OK);
                uploadLook();*//*
                uploadLook();
                break;
            case R.id.add_look_cancel_btn:
                setResult(RESULT_CANCELED);
                finish();
                break;
        }
    }*/

    public void uploadLook() {
        MultipartUploader uploader = new MultipartUploader();
        int countryId = mAppPreferences.getCountry() != null ? mAppPreferences.getCountry().id : -1;
        uploader.uploadLook(this, mAppPreferences.getUUID(), mCatId, countryId, mImageFile, new HttpManager.HttpResultHandler<CommonResult>() {
            public void onResultLoadComplete(CommonResult result) {
                setResult(RESULT_OK);
                finish();
            }
        });
    }
}
